/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package carrello.impl.controller.registereduser;

import carrello.impl.controller.AbstractCTRL;
import carrello.model.association.Invoice;
import carrello.model.entities.PaymentProcessor;
import java.util.Map;
import static carrello.util.EntityManagerUtil.getEntityManager;
import static carrello.util.hiberutil.buildSessionFactory;
import carrello.model.entities.Product;
import carrello.model.entities.User;
import carrello.model.entitydao.ProductDAO;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import org.hibernate.Session;
/**
 * @author mepcotterell
 */
public class ShoppingCartCTRL extends AbstractCTRL {
    
    public ShoppingCartCTRL() {}
    public Map<Integer, Integer> saveToCart(int productid) throws Exception
    {
        Map<Integer, Integer> mapCart;
        Product p  = Product.getProductById(productid);
        if (p != null ){
            mapCart = new HashMap<Integer, Integer>();
            mapCart.put(productid, 1);
            return mapCart;
        } // if
        return null;
     } // saveToCart
    public boolean saveInvoice (Map<Integer, Integer> cart, User u, int pid ) {
        Set<Map.Entry<Integer, Integer>> set = cart.entrySet();

        init();
        Random randomGenerator = new Random();
        for ( Entry<Integer, Integer> v: set ) {
            int prodid = v.getKey();
            int qty = v.getValue();
            Invoice inv = new Invoice ();
            Product prod = Product.getProductById(prodid);
            inv.setProductname(prod.getName());
            inv.setQuantity(qty);
            prod.setQuantity(prod.getQuantity() - qty);
            inv.setCost(prod.getPrice());
            inv.setPurchase_date(new Date());
            inv.setUser(u);
            
            if ( randomGenerator.nextInt(1) == 1 )
                inv.setStatus('1');
            else
                inv.setStatus ('0');
            inv.setProcessor(PaymentProcessor.getPaymentProcessorById(pid));
            getEntityManager().update (prod);
            getEntityManager().store(inv);
        }
        end();
        return true;
    } 
    public int updateCart(Integer quantity)
    {
        if (quantity == 0)
        {
            return 1;
        } else {
            quantity ++;
        }
        return quantity;
    }
    public Map<Product, Integer> getProductInfo(int productId, int quantity)
    {
        Map<Product, Integer> prodMap = new HashMap<Product, Integer>();
        prodMap.put(new ProductDAO().getById(productId), quantity);
        return prodMap;    
        
    }
}
